<script setup lang="ts">
import type { PropType } from 'vue';

import type { PaymentAdjustmentVO } from '#/api/hm/paymentAdjustment/model';

import { h, onMounted, ref } from 'vue';

import {
  Descriptions,
  DescriptionsItem,
  Input,
  message,
  Modal,
  Tag,
} from 'ant-design-vue';

import {
  paymentAdjustmentApprove,
  paymentAdjustmentCancel,
  paymentAdjustmentList,
  paymentAdjustmentReject,
} from '#/api/hm/paymentAdjustment';

defineOptions({ name: 'PaymentAdjustmentList' });

const props = defineProps({
  saleId: {
    type: [Number, String] as PropType<number | string>,
    required: true,
  },
});

const emit = defineEmits(['refresh']);

const { TextArea } = Input;

const loading = ref(false);
const dataList = ref<PaymentAdjustmentVO[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'adjustmentId',
    key: 'adjustmentId',
    width: 80,
    align: 'center',
  },
  {
    title: '调整类型',
    dataIndex: 'adjustmentTypeDesc',
    key: 'adjustmentTypeDesc',
    width: 100,
    align: 'center',
  },
  {
    title: '调整金额',
    dataIndex: 'adjustmentAmount',
    key: 'adjustmentAmount',
    width: 120,
    align: 'right',
  },
  {
    title: '调整前未回款',
    dataIndex: 'originalUnpaidAmount',
    key: 'originalUnpaidAmount',
    width: 120,
    align: 'right',
  },
  {
    title: '调整后未回款',
    dataIndex: 'newUnpaidAmount',
    key: 'newUnpaidAmount',
    width: 120,
    align: 'right',
  },
  {
    title: '申请人',
    dataIndex: 'applicantName',
    key: 'applicantName',
    width: 100,
    align: 'center',
  },
  {
    title: '申请时间',
    dataIndex: 'applyTime',
    key: 'applyTime',
    width: 160,
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    align: 'center',
  },
  {
    title: '审核人',
    dataIndex: 'approverName',
    key: 'approverName',
    width: 100,
    align: 'center',
  },
  {
    title: '审核时间',
    dataIndex: 'approveTime',
    key: 'approveTime',
    width: 160,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
];

// 获取状态标签类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    PENDING: 'warning',
    APPROVED: 'success',
    REJECTED: 'error',
    CANCELLED: 'default',
  };
  return typeMap[status] || 'default';
};

// 查询列表
const fetchList = async () => {
  loading.value = true;
  try {
    const { rows, total } = await paymentAdjustmentList({
      saleId: props.saleId,
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
    });
    dataList.value = rows || [];
    pagination.value.total = total || 0;
  } catch (error) {
    console.error('获取回款调整列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 查看详情
const handleViewDetail = (record: PaymentAdjustmentVO) => {
  Modal.info({
    title: '回款调整详情',
    width: 700,
    content: () => {
      return h('div', {}, [
        h(
          Descriptions,
          { bordered: true, column: 2, size: 'small' },
          {
            default: () =>
              [
                h(
                  DescriptionsItem,
                  { label: '调整记录ID' },
                  () => record.adjustmentId,
                ),
                h(DescriptionsItem, { label: '订单号' }, () => record.saleId),
                h(
                  DescriptionsItem,
                  { label: '客户名称' },
                  () => record.customerName,
                ),
                h(
                  DescriptionsItem,
                  { label: '订单金额' },
                  () => `¥${record.saleAmount}`,
                ),
                h(
                  DescriptionsItem,
                  { label: '调整类型' },
                  () => record.adjustmentTypeDesc,
                ),
                h(
                  DescriptionsItem,
                  { label: '调整金额' },
                  () => `¥${record.adjustmentAmount}`,
                ),
                h(
                  DescriptionsItem,
                  { label: '调整前未回款' },
                  () => `¥${record.originalUnpaidAmount}`,
                ),
                h(
                  DescriptionsItem,
                  { label: '调整后未回款' },
                  () => `¥${record.newUnpaidAmount}`,
                ),
                h(
                  DescriptionsItem,
                  { label: '详细说明', span: 2 },
                  () => record.description,
                ),
                h(
                  DescriptionsItem,
                  { label: '申请人' },
                  () => record.applicantName,
                ),
                h(
                  DescriptionsItem,
                  { label: '申请时间' },
                  () => record.applyTime,
                ),
                h(DescriptionsItem, { label: '状态' }, () =>
                  h(
                    Tag,
                    { color: getStatusType(record.status) },
                    () => record.statusDesc,
                  ),
                ),
                record.approverName
                  ? h(
                      DescriptionsItem,
                      { label: '审核人' },
                      () => record.approverName,
                    )
                  : null,
                record.approveTime
                  ? h(
                      DescriptionsItem,
                      { label: '审核时间' },
                      () => record.approveTime,
                    )
                  : null,
                record.approveRemark
                  ? h(
                      DescriptionsItem,
                      { label: '审核备注', span: 2 },
                      () => record.approveRemark,
                    )
                  : null,
              ].filter(Boolean),
          },
        ),
      ]);
    },
  });
};

// 批准
const handleApprove = async (record: PaymentAdjustmentVO) => {
  let approveRemark = '';

  Modal.confirm({
    title: '批准回款调整',
    content: () => {
      return h('div', {}, [
        h('p', {}, '确定要批准此回款调整申请吗?'),
        h(TextArea, {
          rows: 3,
          placeholder: '请输入审核备注（可选）',
          onInput: (e: any) => {
            approveRemark = e.target.value;
          },
        }),
      ]);
    },
    onOk: async () => {
      try {
        await paymentAdjustmentApprove(record.adjustmentId, approveRemark);
        message.success('审核成功');
        await fetchList();
        emit('refresh');
      } catch (error: any) {
        message.error(error.message || '审核失败');
      }
    },
  });
};

// 驳回
const handleReject = async (record: PaymentAdjustmentVO) => {
  let rejectReason = '';

  Modal.confirm({
    title: '驳回回款调整',
    content: () => {
      return h('div', {}, [
        h('p', {}, '确定要驳回此回款调整申请吗?'),
        h(TextArea, {
          rows: 3,
          placeholder: '请输入驳回原因（必填）',
          onInput: (e: any) => {
            rejectReason = e.target.value;
          },
        }),
      ]);
    },
    onOk: async () => {
      if (!rejectReason?.trim()) {
        message.error('请输入驳回原因');
        throw undefined;
      }

      try {
        await paymentAdjustmentReject(record.adjustmentId, rejectReason);
        message.success('驳回成功');
        await fetchList();
        emit('refresh');
      } catch (error: any) {
        message.error(error.message || '驳回失败');
      }
    },
  });
};

// 取消
const handleCancel = async (record: PaymentAdjustmentVO) => {
  Modal.confirm({
    title: '取消申请',
    content: '确定要取消此申请吗？',
    onOk: async () => {
      try {
        await paymentAdjustmentCancel(record.adjustmentId);
        message.success('取消成功');
        await fetchList();
        emit('refresh');
      } catch (error: any) {
        message.error(error.message || '取消失败');
      }
    },
  });
};

// 分页改变
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  fetchList();
};

onMounted(() => {
  fetchList();
});

defineExpose({
  refresh: fetchList,
});
</script>

<template>
  <div class="payment-adjustment-list">
    <a-table
      :columns="columns"
      :data-source="dataList"
      :loading="loading"
      :pagination="pagination"
      :scroll="{ x: 1400 }"
      row-key="adjustmentId"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'adjustmentAmount'">
          <span :class="record.adjustmentAmount >= 0 ? 'text-red-500' : ''">
            {{ record.adjustmentAmount >= 0 ? '-' : '+' }}¥{{
              Math.abs(record.adjustmentAmount)
            }}
          </span>
        </template>

        <template v-if="column.key === 'originalUnpaidAmount'">
          ¥{{ record.originalUnpaidAmount }}
        </template>

        <template v-if="column.key === 'newUnpaidAmount'">
          ¥{{ record.newUnpaidAmount }}
        </template>

        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusType(record.status)">
            {{ record.statusDesc }}
          </a-tag>
        </template>

        <template v-if="column.key === 'action'">
          <a-space>
            <a-button
              type="link"
              size="small"
              @click="handleViewDetail(record)"
            >
              详情
            </a-button>
            <a-button
              v-if="record.status === 'PENDING'"
              type="link"
              size="small"
              @click="handleApprove(record)"
            >
              批准
            </a-button>
            <a-button
              v-if="record.status === 'PENDING'"
              type="link"
              danger
              size="small"
              @click="handleReject(record)"
            >
              驳回
            </a-button>
            <a-button
              v-if="record.status === 'PENDING'"
              type="link"
              size="small"
              @click="handleCancel(record)"
            >
              取消
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<style scoped>
.payment-adjustment-list {
  padding: 16px 0;
}

.text-red-500 {
  color: #f5222d;
}
</style>
